﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Data.SqlClient;
using Maticsoft.DBUtility;

namespace Template.Web.Admin.handler
{
    /// <summary>
    /// UserHandler 的摘要说明
    /// </summary>
    public class UserHandler : IHttpHandler, IRequiresSessionState
    {
        // 创建对象
        BLL.template_users bll = new BLL.template_users();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            // 结果
            string result = "";
            string action = context.Request["action"];

            // 判断动作
            switch (action)
            {
                // 列表
                case "list":
                    result = list(context);
                    break;
                // 提交
                case "submit":
                    if (string.IsNullOrWhiteSpace(context.Request["id"]))
                    {
                        result = add(context);
                    }
                    else
                    {
                        result = edit(context);
                    }
                    break;
                // 详情
                case "detail":
                    result = detail(context);
                    break;
                // 删除
                case "delete":
                    result = delete(context);
                    break;
                default:
                    break;
            }

            // 输出结果
            context.Response.Write(result);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string list(HttpContext context)
        {
            // 反馈结果
            string result = "{\"errMsg\":\"\"}";

            try
            {
                // 接受参数
                string userName = context.Request["userName"];
                string isDelete = context.Request["isDelete"];

                // where条件
                string strWhere = " 1=1";
                if (!string.IsNullOrWhiteSpace(userName))
                {
                    strWhere += " and username like '%" + userName + "%'";
                }
                if (!string.IsNullOrWhiteSpace(isDelete))
                {
                    strWhere += " and isDelete='" + isDelete + "'";
                }

                // 分页相关参数
                int draw = int.Parse(context.Request["draw"]);
                int length = int.Parse(context.Request["length"]);
                int start = int.Parse(context.Request["start"]);
                int pageIndex = start / length + 1;

                // 获取数据
                int count = bll.GetRecordCount(strWhere); // 总数据条数
                DataSet ds = bll.GetListByPage(strWhere, "uid desc", start, pageIndex * length);
                List<Model.template_users> list = bll.DataTableToList(ds.Tables[0]);

                // 遍历数据
                List<MyUserModel> myList = new List<MyUserModel>();

                foreach (var item in list)
                {
                    // 创建model
                    MyUserModel myModel = new MyUserModel
                    {
                        id = item.uid.ToString(),
                        userName = item.username.ToString(),
                        age = item.age.ToString(),
                        email = item.email.ToString(),
                        mobile = item.mobile.ToString(),
                        idCard = item.idcard.ToString(),
                        head = item.head.ToString(),
                        birthday = item.birthday.ToString(), // 设置反馈格式yyyy-MM-dd hh:mm:ss
                        remark = item.remark.ToString()
                    };

                    // 循环push
                    myList.Add(myModel);
                }

                // 创建listmodel
                MyUserListModel myListModel = new MyUserListModel
                {
                    draw = draw,
                    recordsTotal = count,
                    recordsFiltered = count,
                    data = myList
                };

                // 序列化
                result = JsonConvert.SerializeObject(myListModel);
            }
            catch (Exception ex)
            {
                // 添加错误日志
                //rf_common.logger_error(ex.ToString(), HttpContext.Current);
                result = "{\"errMsg\":\"添加失败," + ex.Message + "\"}";
            }

            return result;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string add(HttpContext context)
        {
            // 反馈结果
            string result = "{\"errMsg\":\"\"}";

            try
            {
                // 接受参数
                string userName = context.Request["userName"];
                string password = context.Request["password"];
                string age = context.Request["age"];
                string email = context.Request["email"];
                string mobile = context.Request["mobile"];
                string idCard = context.Request["idCard"];
                string head = context.Request["head"];
                string birthday = context.Request["birthday"];
                string remark = context.Request["remark"];

                // 创建model
                Model.template_users model = new Model.template_users
                {
                    username = userName,
                    password = "123", // 这里应该转码的
                    //age = int.Parse(age),
                    email = email,
                    mobile = mobile,
                    idcard = idCard,
                    head = head,
                    //birthday = DateTime.Parse(birthday),
                    remark = remark,
                    isdelete = "N"
                };

                // 执行操作
                if (bll.Add(model) <= 0)
                {
                    result = "{\"errMsg\":\"添加失败\"}";
                }
            }
            catch (Exception ex)
            {
                // 添加错误日志
                //rf_common.logger_error(ex.ToString(), HttpContext.Current);
                result = "{\"errMsg\":\"添加失败," + ex.Message + "\"}";
            }

            return result;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string edit(HttpContext context)
        {
            // 反馈结果
            string result = "{\"errMsg\":\"\"}";

            try
            {
                // 接受参数
                string id = context.Request["id"];
                string username = context.Request["username"];
                string age = context.Request["age"];
                string email = context.Request["email"];
                string mobile = context.Request["mobile"];
                string idCard = context.Request["idCard"];
                string head = context.Request["head"];
                string birthday = context.Request["birthday"];
                string remark = context.Request["remark"];

                // 通过ID获取数据
                Model.template_users model = bll.GetModel(int.Parse(id));

                if (model != null)
                {
                    model.username = username;
                    model.age = int.Parse(age);
                    model.email = email;
                    model.idcard = idCard;
                    model.head = head;
                    //model.birthday = DateTime.Parse(birthday);
                    model.remark = remark;

                    // 执行操作
                    if (bll.Update(model) == false)
                    {
                        result = "{\"errMsg\":\"更新失败\"}";
                    }
                }
            }
            catch (Exception ex)
            {
                // 添加错误日志
                //rf_common.logger_error(ex.ToString(), HttpContext.Current);
                result = "{\"errMsg\":\"更新失败," + ex.Message + "\"}";
            }

            return result;
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string detail(HttpContext context)
        {
            // 反馈结果
            string result = "{\"errMsg\":\"\"}";

            try
            {
                // 接受参数
                string id = context.Request["id"];

                // 通过ID获取数据
                Model.template_users model = bll.GetModel(int.Parse(id));

                if (model != null)
                {
                    // 创建model
                    MyUserModel myModel = new MyUserModel
                    {
                        id = model.uid.ToString(),
                        userName = model.username.ToString(),
                        age = model.age.ToString(),
                        email = model.email.ToString(),
                        mobile = model.mobile.ToString(),
                        idCard = model.idcard.ToString(),
                        head = model.head.ToString(),
                        birthday = model.birthday.ToString(), // 设置反馈格式yyyy-MM-dd hh:mm:ss
                        remark = model.remark.ToString()

                    };

                    // 序列化
                    result = JsonConvert.SerializeObject(myModel);
                }

            }
            catch (Exception ex)
            {
                // 添加错误日志
                //rf_common.logger_error(ex.ToString(), HttpContext.Current);
                result = "{\"errMsg\":\"获取详情失败," + ex.Message + "\"}";
            }

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string delete(HttpContext context)
        {
            string result = "{\"errMsg\":\"\"}";

            try
            {
                string id = context.Request["id"];

                if (bll.Delete(int.Parse(id)) == false)
                {
                    result = "{\"errMsg\":\"删除失败\"}";
                }
            }
            catch (Exception ex)
            {
                // 添加错误日志
                //rf_common.logger_error(ex.ToString(), HttpContext.Current);
                result = "{\"errMsg\":\"删除失败," + ex.Message + "\"}";
            }
            return result;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public struct MyUserListModel
    {
        public int draw;
        public int recordsTotal;
        public int recordsFiltered;
        public List<MyUserModel> data;
    }

    public struct MyUserModel
    {
        public string id;
        public string userName;
        public string age;
        public string email;
        public string mobile;
        public string idCard;
        public string head;
        public string birthday;
        public string remark;
    }
}